export class PerformanceMonitor {
    constructor() {
        this.fps = 0;
        this.frameTime = 0;
        this.frames = 0;
        this.lastTime = performance.now();
        this.memoryUsage = 0;
        this.resourceLoadTimes = new Map();
        this.sceneTransitionTimes = new Map();
        
        // 性能数据存储
        this.metrics = {
            fps: [],
            frameTime: [],
            memory: [],
            loadTimes: [],
            transitionTimes: []
        };
        
        // 开始监控
        this.startMonitoring();
    }

    startMonitoring() {
        this.monitoringInterval = setInterval(() => {
            this.updateMetrics();
        }, 1000);
    }

    stopMonitoring() {
        if (this.monitoringInterval) {
            clearInterval(this.monitoringInterval);
        }
    }

    // 更新性能指标
    updateMetrics() {
        const currentTime = performance.now();
        const elapsed = currentTime - this.lastTime;
        
        // 计算FPS
        this.fps = Math.round((this.frames * 1000) / elapsed);
        this.frameTime = elapsed / this.frames;
        
        // 记录数据
        this.metrics.fps.push(this.fps);
        this.metrics.frameTime.push(this.frameTime);
        
        // 如果可用，记录内存使用
        if (wx.getPerformance && wx.getPerformance().memory) {
            this.memoryUsage = wx.getPerformance().memory.usedJSHeapSize;
            this.metrics.memory.push(this.memoryUsage);
        }
        
        // 重置计数器
        this.frames = 0;
        this.lastTime = currentTime;
    }

    // 记录帧渲染
    recordFrame() {
        this.frames++;
    }

    // 开始记录资源加载时间
    startResourceLoad(resourceId) {
        this.resourceLoadTimes.set(resourceId, performance.now());
    }

    // 结束记录资源加载时间
    endResourceLoad(resourceId) {
        const startTime = this.resourceLoadTimes.get(resourceId);
        if (startTime) {
            const loadTime = performance.now() - startTime;
            this.metrics.loadTimes.push({
                resourceId,
                loadTime
            });
            this.resourceLoadTimes.delete(resourceId);
        }
    }

    // 记录场景切换时间
    recordSceneTransition(fromScene, toScene) {
        const transitionId = `${fromScene}->${toScene}`;
        const startTime = performance.now();
        
        return () => {
            const transitionTime = performance.now() - startTime;
            this.metrics.transitionTimes.push({
                from: fromScene,
                to: toScene,
                time: transitionTime
            });
        };
    }

    // 获取性能报告
    getPerformanceReport() {
        const avgFps = this.calculateAverage(this.metrics.fps);
        const avgFrameTime = this.calculateAverage(this.metrics.frameTime);
        const avgMemory = this.calculateAverage(this.metrics.memory);
        
        return {
            fps: {
                average: avgFps,
                min: Math.min(...this.metrics.fps),
                max: Math.max(...this.metrics.fps)
            },
            frameTime: {
                average: avgFrameTime,
                min: Math.min(...this.metrics.frameTime),
                max: Math.max(...this.metrics.frameTime)
            },
            memory: {
                average: avgMemory,
                min: Math.min(...this.metrics.memory),
                max: Math.max(...this.metrics.memory)
            },
            resourceLoading: {
                times: this.metrics.loadTimes,
                average: this.calculateAverage(this.metrics.loadTimes.map(t => t.loadTime))
            },
            sceneTransitions: {
                times: this.metrics.transitionTimes,
                average: this.calculateAverage(this.metrics.transitionTimes.map(t => t.time))
            }
        };
    }

    // 计算平均值
    calculateAverage(array) {
        if (!array.length) return 0;
        return array.reduce((a, b) => a + b, 0) / array.length;
    }

    // 清理数据
    clear() {
        this.metrics = {
            fps: [],
            frameTime: [],
            memory: [],
            loadTimes: [],
            transitionTimes: []
        };
        this.resourceLoadTimes.clear();
    }
} 